// 防抖
export function debounce<T extends (...args: any[]) => void>(
  func: T,
  wait: number,
  immediate?: boolean,
): (...args: Parameters<T>) => void {
  let timeout: number | null = null
  return function (...args: Parameters<T>) {
    const later = () => {
      timeout = null
      if (!immediate) func.apply(this, args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout as number)
    timeout = window.setTimeout(later, wait)
    if (callNow) func.apply(this, args)
  }
}
// 节流
export function throttle<T extends (...args: any[]) => void>(
  func: T,
  limit: number,
): (...args: Parameters<T>) => void {
  let lastFunc: number | null = null
  let lastRan: number | null = null
  return function (...args: Parameters<T>) {
    const context = this
    const now = new Date().getTime()
    if (!lastRan) {
      func.apply(context, args)
      lastRan = now
    } else {
      clearTimeout(lastFunc as number)
      lastFunc = window.setTimeout(
        function () {
          if (now - lastRan >= limit) {
            func.apply(context, args)
            lastRan = now
          }
        },
        limit - (now - lastRan),
      )
    }
  }
}
